import Vue from "vue";
import VueRouter from "vue-router";
import defaultRouter from "./defaultRouter.js";
import { loopRouter } from "./routerUtils.js";
import store from "@/store/index.js";
import auth from "@/utils/auth.js";
import { goLogin } from "@/utils/browser.js";

//解决router-link点击报错的问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

Vue.use(VueRouter);

const createRouter = () => {
  return  new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    hasFirstRoute: true,
    routes: defaultRouter,
  });
}

const router = createRouter();

router.beforeEach(async (to, from, next) => {
  const { hasFirstRoute } = router.options;
  const token = auth.hasToken();
  
  // 如果没有token并且访问的不是登录页面那就跳转登录页面
  if (!token && to.path !== "/login") {
    router.options.hasFirstRoute = true;
    return next("/login");
  }
  // 如果有token，但是访问的是login页面那就哪里来的回去哪里
  if (token && to.path === "/login") {
    return next(from.path);
  }

  // 如果有token并且hasFirstRoute为第一次访问获取用户菜单角色信息
  if (token && hasFirstRoute) {
    await store.dispatch("getUserInfo");
    router.options.hasFirstRoute = false;
    return next(to.fullPath);
  }

  next();
});

export const addRouter = (menuList) => {
  loopRouter(router, menuList);
  // 添加完默认的在添加统配符路由,不然会导致动态路由没有添加完，自动跳转404了
  router.addRoute({
    path: "*",
    redirect: "/page404",
  });
};

export const resetRouter = () => {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher;
  router.options.hasFirstRoute = true;
  goLogin();
}

export default router;
